package com.autonavi.yunda.yunji.controller;

import com.autonavi.yunda.yunji.common.exception.AmapPreconditions;
import com.autonavi.yunda.yunji.controller.interceptor.NeedOperationLog;
import com.autonavi.yunda.yunji.core.enums.OperationRecordType;
import com.autonavi.yunda.yunji.core.model.dto.ProjectDTO;
import com.autonavi.yunda.yunji.core.model.mappers.ProjectMapper;
import com.autonavi.yunda.yunji.core.service.ProjectService;
import com.autonavi.yunda.yunji.core.service.thirdpartyservice.FalconInterfaceService;
import com.autonavi.yunda.yunji.core.vo.response.ProjectVO;
import com.autonavi.yunda.yunji.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author cizhong.wcs
 * @date 2022/3/7 7:33 下午
 */
@Slf4j
@RestController
@RequestMapping("/project")
public class ProjectController {

    @Resource
    private ProjectAuthService projectAuthService;
    @Resource
    private OperationRecordService operationRecordService;
    @Resource
    private FalconInterfaceService falconInterfaceService;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private BucUserService bucUserService;
    @Resource
    private UserProjectService userProjectService;
    @Resource
    private ProjectService projectService;
    @Resource
    private LocalizationService localizationService;
    @Resource
    private FactoryUserService factoryUserService;

    @NeedOperationLog(operationName = "project.add")
    @PostMapping("add")
    public Long add(@RequestBody ProjectVO request) {
        ProjectDTO dto = request.toAddDto(bucUserService.getCurEmployeeIdOrNull());
        AmapPreconditions.checkArgumentForUser(
                projectService.findByName(request.getName()) == null,
                "该项目名称已存在,请调整项目名称:" + request.getName()
        );
        if (Strings.isBlank(dto.getFalconProjectId())) {
            String falconProjectId = falconInterfaceService.createFalconProject(dto.getName(), dto.getDescription(), bucUserService.getCurEmployeeIdOrNull());
            dto.setFalconProjectId(falconProjectId);
        }
        dto.setBdId(factoryUserService.getCurrentUserBdId());
        Long id = projectService.add(dto);
        operationRecordService.add(OperationRecordType.ProjectSubType.CREATE, dto.getProjectId());
        //将新创建的项目授权给当前用户
        userProjectService.addUserProjectId(
                bucUserService.getCurEmployeeId(),
                dto.getProjectId(),
                bucUserService.getCurEmployeeId()
        );
        return id;
    }

    /**
     * 根据projectId更新字段
     */
    @NeedOperationLog(operationName = "project.update")
    @PostMapping("update")
    public String update(@RequestBody ProjectVO request) {
        UpdateWrapper<ProjectDTO> wrapper = request.toUpdateWrapper(bucUserService.getCurEmployeeIdOrNull());
        projectAuthService.checkProjectPermission(request.getProjectId());
        projectService.update(wrapper);
        operationRecordService.add(OperationRecordType.ProjectSubType.UPDATE, request.getProjectId());
        return "success";
    }

    @GetMapping("listAll")
    public List<ProjectVO> listAll() {
        return projectAuthService.listAllAuthorizedProjects();
    }

    @NeedOperationLog(operationName = "project.deleteByProjectId")
    @GetMapping("deleteByProjectId")
    public void deleteByProjectId(@RequestParam String projectId) {
        projectAuthService.checkProjectPermission(projectId);
        projectService.deleteByProjectId(projectId);
        operationRecordService.add(OperationRecordType.ProjectSubType.DELETE, projectId);
    }


    /**
     * todo 为了刷新falcon中的项目所使用,后续删除
     */
    @GetMapping("refreshFalconProjects")
    public void refreshProjects(@RequestParam List<String> projectIds) {
        AmapPreconditions.checkArgument(!CollectionUtils.isEmpty(projectIds));
        QueryWrapper<ProjectDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("project_id", projectIds);
        List<ProjectDTO> projectDTOList = projectMapper.selectList(queryWrapper);
        for (ProjectDTO projectDTO : projectDTOList) {
            try {
                String falconProjectId = falconInterfaceService.createFalconProject(projectDTO.getName(), projectDTO.getDescription(), bucUserService.getCurEmployeeIdOrNull());
                projectDTO.setFalconProjectId(falconProjectId);
                projectMapper.updateById(projectDTO);
                log.info("更新项目falcon成功,projectId = {},falconId = {}", projectDTO.getProjectId(), falconProjectId);
            } catch (Exception e) {
                log.error("更新项目falconId失败,projectId = {}", projectDTO.getProjectId(), e);
            }
        }
    }

    /**
     * 本地化
     *
     * @param projectId 项目ID
     * @param response  http response
     * @return 成功返回success
     */
    @NeedOperationLog(operationName = "project.localization")
    @GetMapping("localization")
    public String localization(@RequestParam String projectId, HttpServletResponse response) {
        log.info("projectId is {}", projectId);
        String res = localizationService.exportLocalizationFileByProjectId(projectId, response);
        operationRecordService.add(OperationRecordType.ProjectSubType.EXPORT, projectId);
        return res;
    }
}
